package com.nowcoder.community.controller.advice;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName ExceptionAdvice
 * @Description
 * @Author hhwu
 * @Date 2022/5/24 21:42
 * Version 1.0
 **/
// springboot如果出现指定异常，会自动被该类捕获
@ControllerAdvice(annotations = Controller.class)// 仅自动扫描带有controller注解的bean
public class ExceptionAdvice {
    /**
     * @Author hhwu
     * @Description //TODO Controller的全局配置类，可以统一处理Controller 的异常，绑定数据等等
     * @Date 21:45 2022/5/24
     **/

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})// 该注解表示下面的方法是用来处理异常的，括号内指明处理的异常类型
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        /**
         * @Author hhwu
         * @Description //TODO 统一异常处理，然后根局异常的原因是json还是页面，跳转到json或者500
         * @Date 21:56 2022/5/24
         * @Param [e, request, response]
         * @return void
         **/
        logger.error("服务器发生异常:" + e.getMessage());
        // logger记录详细的异常信息
        for (StackTraceElement element :
                e.getStackTrace()) {
            logger.error(element.toString());
        }

        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {// 如果是异步请求
            // 响应json格式的字符串
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器异常"));
        } else {// 如果是一般程序发生的异常
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }
}
